/*
 * can.c
 *
 *  Created on: Aug 17, 2025
 *      Author: Young
 */
#include "can.h"

/**
 * externs
 *
 */
extern CAN_HandleTypeDef hcan;

/**
 * globals
 *
 */
uint8_t canRxBuffer[8];

/**
 * canSend
 *
 * @param
 * @return
 */
int canSend(void) {
	static uint8_t cycle;

	CAN_TxHeaderTypeDef txHeader;
	txHeader.ExtId = 0x19FF0891;
	txHeader.IDE = CAN_ID_EXT;
	txHeader.RTR = CAN_RTR_DATA;
	txHeader.DLC = 8;

	uint8_t aData[8];

	aData[0] = 7;
	aData[1] = 6;
	aData[2] = 5;
	aData[3] = 4;
	aData[4] = 3;
	aData[5] = 2;
	aData[6] = 1;
	aData[7] = cycle++;

	uint32_t txMailbox = 0;

	if (HAL_CAN_AddTxMessage(&hcan, &txHeader, aData, &txMailbox) != HAL_OK) {
		return -1;
	};
	return 0;
}

/**
 * task1s
 *
 */
void task1sCan(void) {

//	canSend();
}

/**
 * timeTask
 *
 */
void timeTaskCan(void) {
	// 系统时基
	static __IO uint32_t lastTick = 0;
	int32_t delta = tickDelta(&lastTick);
	// 1s
	static uint16_t ms1k;
	ms1k += delta;
	if (ms1k >= 1000) {
		ms1k = 0;
		task1sCan();
	}
}

/**
 * canSetup
 *
 * @param
 * @return
 */
void canSetup(void) {

}

/**
 * canLoop
 *
 * @param
 * @return
 */
void canLoop(void) {
	// 定时任务
	timeTaskCan();
}

/**
 * CAN FIFO0接收中断
 *
 */
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) {

	CAN_RxHeaderTypeDef rxHeader;
	uint8_t rxData[8];

	if (HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &rxHeader, rxData) == HAL_OK) {
		//判断ID为扩展ID
		if (rxHeader.IDE == CAN_ID_EXT) {
			//判断是否为自己需要的ID
			if (rxHeader.ExtId == 0x19FF0892) {
				canSend();
			}
		}
	}
}
